#include "paneledmainwindow.h"

PaneledMainWindow::PaneledMainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    tabWidget = new QTabWidget(this);
    tabWidget->setMovable(true);
    dockWidgetList = new QList<QDockWidget*>();
    this->setCentralWidget(tabWidget);
}

void PaneledMainWindow::addDockWidget(Qt::DockWidgetArea area, QDockWidget *dockwidget)
{
    QMainWindow::addDockWidget(area,dockwidget);
    dockWidgetList->append(dockwidget);
    dockwidget->installEventFilter(this);
}

void PaneledMainWindow::addDockWidget(Qt::DockWidgetArea area, QDockWidget *dockwidget, Qt::Orientation orientation)
{
    QMainWindow::addDockWidget(area,dockwidget,orientation);
    dockWidgetList->append(dockwidget);
    dockwidget->installEventFilter(this);
}

bool PaneledMainWindow::eventFilter(QObject *obj, QEvent *ev)
{
    foreach (QDockWidget *dockWidget, *dockWidgetList) {
        if(obj == dockWidget)
        {
            if(ev->type() == QEvent::Move)
            {
                bool ret = QMainWindow::eventFilter(obj,ev);
                if(QApplication::mouseButtons().testFlag(Qt::LeftButton))
                {
                    dockWidget->setProperty("clicked",(QVariant)true);
                }
                return ret;
            }
            else if(ev->type() == QEvent::MouseButtonRelease)
            {
                bool ret = QMainWindow::eventFilter(obj,ev);
                QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(ev);
                if(mouseEvent->button() == Qt::LeftButton)
                {
                    if(dockWidget->property("clicked") == (QVariant)true)
                    {
                        dockWidget->setProperty("clicked",(QVariant)false);
                        if(this->centralWidget()->geometry().contains(dockWidget->geometry().topLeft()))
                        {
                            QWidget* widget = dockWidget->widget();
                            widget->setParent(this);
                            tabWidget->addTab(widget,dockWidget->windowTitle());
                            dockWidget->setFeatures(QDockWidget::DockWidgetClosable |
                                                    QDockWidget::DockWidgetFloatable |
                                                    QDockWidget::DockWidgetMovable);
                            dockWidget->close();
                        }
                    }
                }
                return ret;
            }
            else
                return false;
        }
    }
    return QMainWindow::eventFilter(obj,ev);
}
